import React, { useEffect, useState } from 'react';
import { Form, Button, Typography, Flex, message, Col, Input, Select, Divider } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import RequestUploadItem from '../../Components/RequestUploadItem';
import RequestFormProjectTpl from '../../Components/RequestFormProjectTpl';
import RequestFormProductTpl from '../../Components/RequestFormProductTpl';
import { useLocation, useNavigate } from 'react-router-dom';
import { apiSysTemplateInitiate } from '../../../services/common';
import { apiExperimentalDataAdd, apiExperimentalDataView, apiExperimentalDataEdit } from '../../../services/experimentalData/request';
import { apiMSDTagSelect, apiMSDTagBatchAdd } from '../../../services/masterData/tag';
import { ACCEPT_TYPE, REQUEST_PAGE, APPROVAL_STATUS, RES_MODE } from '../../../utils/constant';
import DeleteConfirm from '../../Components/DeleteConfirm';
import { getUserName, resquestDetialAttachmentListFormat, transformArray, formatRequestItemData } from '../../../utils/commonUtil';
import _ from 'lodash';
import RequestApprovalBtn from '../../Components/RequestApprovalBtn';

const { Title } = Typography;
const ExperimentalDataRequestDetails = () => {
  const { APPROVED, REJECTED, PENDING, DRAFT } = APPROVAL_STATUS;
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const location = useLocation();
  if (!location?.state) {
    navigate('/experimentalData/list');
  };
  const queryParams = location?.state || {};
  const { tplId, tBu, experimentalProjectId, editMode, approveRequestSituationId, tMd, tTm } = queryParams;
  const [initialValues, setInitialValues] = useState();
  const [compTagList, setCompTagList] = useState([]);
  const [masterDataTagList, setMasterDataTagList] = useState([]);


  // mock permission
  const isCampAdmin = true;
  const isBuPRPD = false;
  const isBuAdmin = false;
  const isBuTester = false;

  const apiExperimentalDataSaveAsync = async (type) => {
    const formData = form?.getFieldsValue();
    // 将components中的tag的类型数组改为字符串
    formData?.product?.forEach(item => {
      item?.components?.forEach(component => {
        if (Array.isArray(component?.tag)) {
          component.tag = component?.tag?.join(',');
        }
      });
    });

    const prjData = {
      product: formData?.product,
      project: formData?.project,
      userId: getUserName(),
      operationType: type,
    };
    const data = editMode === RES_MODE.NEW ? await apiExperimentalDataAdd(prjData) : await apiExperimentalDataEdit(prjData);
    // console.log(data);
    if (data?.data?.code === 200) {
      message.success(t('common.saveSuccess'));
      if (formData?.project?.requestStatus?.fieldValue === APPROVED) {
        setUpTagAndSave();
      };
      navigate('/experimentalData/list')
    }
  };

  // 将新增tag存入master data
  const setUpTagAndSave = () => {
    // 获取所有tag并去重
    const formData = form?.getFieldsValue();
    const allTaglist = extractTags(formData?.product);
    // 移除master data的已有tag
    const filteredArray = allTaglist.filter(item => !masterDataTagList.includes(item));
    // console.log('====filteredArray',filteredArray);
    apiMSDTagBatchAddAsync(filteredArray);
  }

  const extractTags = (data) => {
    const tagsArray = [];
    data?.forEach(item => {
      item?.components?.forEach(component => {
        tagsArray.push(...(component.tag)?.split(','));
      });
    });
    return [...new Set(tagsArray)];
  }

  const apiMSDTagBatchAddAsync = (filteredArray) => {
    const productList = form?.getFieldsValue()?.project;
    const params = {
      buType: productList?.buType?.fieldValue,
      moduleName: productList?.moduleName?.fieldValue,
      tags: filteredArray,
      userId: getUserName()
    }
    apiMSDTagBatchAdd(params).then((res) => {
      if (res?.data) {
        message.success(t('common.tagSuccess'));
      }
    })
  }

  const apiMSDTagSelectAsync = (productListName) => {
    const params = {
      buType: productListName.buType.fieldValue,
      moduleName: productListName.moduleName.fieldValue
    }
    apiMSDTagSelect(params).then((res) => {
      if (res?.data) {
        setCompTagList(transformArray(res.data.data.item));
        setMasterDataTagList(res.data.data.item);
      }
    })
  }

  const saveClickHandle = (type) => {
    form.validateFields().then(() => {
      apiExperimentalDataSaveAsync(type);
    }, () => {
      return false;
    });
  };

  const delListItemHandle = (remove, index) => {
    DeleteConfirm({
      t,
      title: t('common.deleteMsg'),
      onOk () {
        remove && remove(index);
      }
    });
  };

  // 实验数据部分
  const productExtraContentrRender = (index) => {
    const listNames = 'product';
    const productFileList = resquestDetialAttachmentListFormat(initialValues?.[listNames]?.[index]?.productAttachmentUrl?.fieldValue);
    const testMethodFileList = resquestDetialAttachmentListFormat(initialValues?.[listNames]?.[index]?.testMethodAttachmentUrl?.fieldValue);
    return (
      <>
        <div>
          <Flex>
            <Col span={12} >
              <Form.Item
                labelCol={{ span: 24 }}
                wrapperCol={{ span: 24 }}
                name={[index, 'productAttachmentUrl']}
                label={t('experimentalData.productAttachment')}>
                <RequestUploadItem
                  btnText={t('common.upload')}
                  acceptType={ACCEPT_TYPE.XLS}
                  disabled={initialValues?.project?.requestStatus?.fieldValue === APPROVED && editMode === RES_MODE.VIEW}
                  uploadUpdateFn={({ fileList, deleteFileList }) => {
                    const productData = form?.getFieldsValue()?.[listNames];
                    const productItemData = form?.getFieldsValue()?.[listNames]?.[index];
                    productData[index] = {
                      ...productItemData,
                      productAttachmentUrl: {
                        fieldName: 'productAttachmentUrl',
                        fieldValue: fileList,
                        fieldDeleteValue: deleteFileList,
                      }
                    };
                    form.setFieldsValue({
                      [listNames]: productItemData,
                    });
                    // form.validateFields([listNames]);
                  }}
                  fileListData={productFileList}
                />
              </Form.Item>
            </Col>
            <Col span={12} >
              <Form.Item
                labelCol={{ span: 24 }}
                wrapperCol={{ span: 24 }}
                name={[index, 'testMethodAttachmentUrl']}
                label={t('experimentalData.testMethodAttachment')}>
                <RequestUploadItem
                  btnText={t('common.upload')}
                  acceptType={ACCEPT_TYPE.XLS}
                  disabled={initialValues?.project?.requestStatus?.fieldValue === APPROVED && editMode === RES_MODE.VIEW}
                  uploadUpdateFn={({ fileList, deleteFileList }) => {
                    const productData = form?.getFieldsValue()?.[listNames];
                    const productItemData = form?.getFieldsValue()?.[listNames]?.[index];
                    productData[index] = {
                      ...productItemData,
                      testMethodAttachmentUrl: {
                        fieldName: 'testMethodAttachmentUrl',
                        fieldValue: fileList,
                        fieldDeleteValue: deleteFileList,
                      }
                    };
                    form.setFieldsValue({
                      [listNames]: productItemData,
                    });
                    // form.validateFields([listNames]);
                  }}
                  fileListData={testMethodFileList}
                />
              </Form.Item>
            </Col>
          </Flex>
        </div>
        
        <Divider></Divider>
        <Col span={24}>
          <Form.List name={[index, 'components']}>
            {(fields, { add, remove }) => (
              <div
                style={{
                  marginBottom: '24px',
                  display: 'flex',
                  rowGap: 10,
                  flexDirection: 'column'
                }}
              >
                {fields.map((field, componentsIndex) => {
                  return (
                    <>
                      <Flex justify="space-between" align="center">
                        <div style={{ fontWeight: 700 }}>{'Component ' + (Number(componentsIndex) + 1)}</div>
                        <Button
                          type="text"
                          disabled={initialValues?.project?.requestStatus?.fieldValue === APPROVED && editMode === RES_MODE.VIEW}
                          icon={<DeleteOutlined style={{ fontSize: 18, color: '#b14124', }} />}
                          onClick={() => {
                            delListItemHandle(remove, field.name);
                          }}
                        />
                      </Flex>
                      <Flex>
                        <Col>
                          <Form.Item labelCol={{ span: 24 }}
                            wrapperCol={{ span: 24 }} label={t('experimentalData.name')} name={[field.name, 'componentName']}>
                            <Input placeholder={t('common.PleaseInput')} disabled={initialValues?.project?.requestStatus?.fieldValue === APPROVED && editMode === RES_MODE.VIEW} allowClear />
                          </Form.Item>
                        </Col>
                        <Col>
                          <Form.Item labelCol={{ span: 24 }}
                            wrapperCol={{ span: 24 }} label={t('experimentalData.wt')} name={[field.name, 'wt']}>
                            <Input placeholder={t('common.PleaseInput')} disabled={initialValues?.project?.requestStatus?.fieldValue === APPROVED && editMode === RES_MODE.VIEW} allowClear />
                          </Form.Item>
                        </Col>
                        <Col>
                          <Form.Item labelCol={{ span: 24 }}
                            wrapperCol={{ span: 24 }} label={t('experimentalData.supplier')} name={[field.name, 'supplier']}>
                            <Input placeholder={t('common.PleaseInput')} disabled={initialValues?.project?.requestStatus?.fieldValue === APPROVED && editMode === RES_MODE.VIEW} allowClear />
                          </Form.Item>
                        </Col>
                        <Col>
                          <Form.Item labelCol={{ span: 24 }}
                            wrapperCol={{ span: 24 }} label={t('experimentalData.rawMaterial')} name={[field.name, 'rawMaterial']}>
                            <Input placeholder={t('common.PleaseInput')} disabled={initialValues?.project?.requestStatus?.fieldValue === APPROVED && editMode === RES_MODE.VIEW} allowClear />
                          </Form.Item>
                        </Col>
                      </Flex>
                      <Col span={24}>
                        <Form.Item labelCol={{ span: 24 }} wrapperCol={{ span: 24 }} name={[field.name, 'tag']} label={t('experimentalData.tag')} >
                          <Select
                            options={compTagList}
                            disabled={initialValues?.project?.requestStatus?.fieldValue === APPROVED && editMode === RES_MODE.VIEW}
                            mode="tags"
                            placeholder={t('common.pleaseSelect')}
                            allowClear
                          />
                        </Form.Item>
                      </Col>
                      <Divider></Divider>
                    </>
                  )
                })}

                <Button type="primary" disabled={initialValues?.project?.requestStatus?.fieldValue === APPROVED && editMode === RES_MODE.VIEW} ghost style={{ width: "132px" }} onClick={() => add()} block>
                  {t('experimentalData.addComponent')}
                </Button>
              </div>
            )}
          </Form.List>
        </Col>
      </>
    )
  };

  useEffect(() => {
    // 获取模板数据
    let initData = {};
    if (tplId && editMode === RES_MODE.NEW) {
      apiSysTemplateInitiate({ templateName: tTm, buType: tBu, moduleName: tMd }).then((res) => {
        if (res?.data?.code === 200) {
          initData = {
            project: res?.data?.data?.Project,
            product: [
              {
                ...res?.data?.data?.Product
              }
            ]
          };
          setInitialValues(initData);
        }
      })
    } else if (experimentalProjectId && (editMode === RES_MODE.APPROVAL || editMode === RES_MODE.VIEW || editMode === RES_MODE.EDIT || editMode === RES_MODE.TESTEREDIT)) {
      apiExperimentalDataView({
        experimentalProjectId: experimentalProjectId,
        userId: getUserName(),
      }).then((res) => {
        if (res?.data?.code === 200) {
          const newProject = formatRequestItemData(res?.data?.data?.item?.project);
          const newProduct = res?.data?.data?.item?.product?.map((prdItem) => {
            return formatRequestItemData(prdItem)
          });
          if (newProject?.requestStatus?.fieldValue === APPROVED) {
            newProduct.map((item) => {
              if (item?.components?.length === 0) {
                // approved flow 默认components展示第一个
                item.components.push({ componentName: '' })
              } else {
                // 将components中的tag的类型字符串改为数组
                item?.components?.forEach(component => {
                  component.tag = component?.tag?.split(',');
                });
              }
            })
            apiMSDTagSelectAsync(newProject);
          }
          initData = {
            project: newProject,
            product: newProduct,
          };
          setInitialValues(initData);

        }
      })
    };
  }, []);

  return (
    <>
      {
        initialValues &&
        <>
          <div className='page-title-wrap'>
            <Flex align='center' justify='space-between'>
              <Title className='fontStyleH2' level={2} >{editMode === RES_MODE.NEW ? t(`common.newRequest`) : t(`common.requestDetail`)}</Title>
              <div>
                <RequestApprovalBtn
                  approveRequestSituationId={approveRequestSituationId}
                  form={form}
                  moduleConfig={REQUEST_PAGE['Experimental Data']}
                  initialValues={initialValues}
                  editMode={editMode}
                />
                {
                  (
                    //可填写测试数据 save
                    ((isCampAdmin || isBuPRPD || isBuAdmin || isBuTester) && initialValues?.project?.requestStatus?.fieldValue === APPROVED) ||
                    //可重新编辑 save
                    ((isCampAdmin || isBuPRPD || isBuAdmin) && (initialValues?.project?.requestStatus?.fieldValue === DRAFT || initialValues?.project?.requestStatus?.fieldValue === REJECTED || initialValues?.project?.requestStatus?.fieldValue === APPROVED || editMode === RES_MODE.NEW))
                  ) && editMode !== RES_MODE.VIEW &&
                  <Button onClick={() => { saveClickHandle('save') }} style={{ marginRight: '10px' }}>{t('common.save')}</Button>
                }
                {

                  //可重新编辑 submit
                  (isCampAdmin || isBuPRPD || isBuAdmin) && (initialValues?.project?.requestStatus?.fieldValue === DRAFT || initialValues?.project?.requestStatus?.fieldValue === REJECTED || editMode === RES_MODE.NEW) && editMode !== RES_MODE.VIEW &&
                  <Button type='primary' onClick={() => { saveClickHandle('submit') }}>{t('common.submit')}</Button>
                }
              </div>
            </Flex>
          </div>
          <div className='page-content-wrap'>
            <Form form={form}
              initialValues={initialValues}
              disabled={editMode === RES_MODE.VIEW || editMode === RES_MODE.TESTEREDIT || editMode === RES_MODE.APPROVAL}
            >
              {/* Project */}
              <RequestFormProjectTpl
                uploadParams={{ type: 'experimentalData', name: 'project' }}
                tplData={queryParams}
                listNames='project'
                form={form}
                initialValues={initialValues}
                editMode={editMode}
                moduleConfig={REQUEST_PAGE['Experimental Data']}
              />
              {/* Product */}
              <RequestFormProductTpl
                uploadParams={{ type: 'experimentalData', name: 'product' }}
                listNames='product'
                form={form}
                initialValues={initialValues}
                productExtraContentrRender={productExtraContentrRender}
                editMode={editMode}
                moduleConfig={REQUEST_PAGE['Experimental Data']}
              />
            </Form>
          </div>
        </>
      }
    </>
  )
};

export default ExperimentalDataRequestDetails;
